package com.hrpmar.service.impl;

import com.hrpmar.controller.dto.DestoryDto;
import com.hrpmar.controller.dto.DrugstockDto;
import com.hrpmar.controller.dto.TakestoDto;
import com.hrpmar.mapper.*;
import com.hrpmar.pojo.*;
import com.hrpmar.service.DrugstockService;
import com.hrpmar.service.PurplanService;
import com.hrpmar.utils.Pager;
import com.hrpmar.utils.genNumUtil;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by 李松松 on 2017/11/20.
 */
@Service
@Transactional
public class DrugstockServiceImpl implements DrugstockService {

    @Resource
    private DrugstockMapper drugstockMapper;
    @Resource
    private DruginfoMapper druginfoMapper;
    @Resource
    private PurplanService purplanService;
    @Resource
    private DestorymasterMapper destorymasterMapper;
    @Resource
    private DestorydetailsMapper destorydetailsMapper;
    @Resource
    private WorkerMapper workerMapper;
    @Resource
    private InventoryingMapper inventoryingMapper;
    @Resource
    private InvdetailsMapper invdetailsMapper;

    @Override
    public Pager searchDrugstock(DrugstockDto dto, Integer offset, Integer limit) {
        Pager pager = new Pager();
        pager.setRows(drugstockMapper.searchDrugStork(dto, offset, limit));
        pager.setTotal(drugstockMapper.searchDrugStockCount(dto));
        return pager;
    }

    @Override
    public List<Druginfo> searchDrugstockName() {
        return drugstockMapper.searchDeugstockName();
    }

    @Override
    public Pager searchDetailBydrunNum(DrugstockDto dto, Integer offset, Integer limit) {
        Pager pager = new Pager();
        pager.setRows(drugstockMapper.searchdetailedBydrunNum(dto, offset, limit));
        pager.setTotal(drugstockMapper.searchDetailCount(dto));
        return pager;
    }

    @Override
    public Druginfo searchByNum(String drugNum) {
        return druginfoMapper.getDrugByNum(drugNum);
    }

    @Override
    public Integer updateDrugstockInfoAspect(Drugstock drugstock) {
        return drugstockMapper.updateDrugstockInfo(drugstock);
    }

    @Override
    public Pager searchDrugstockinsufficient(DrugstockDto dto, Integer offset, Integer limit) {
        Pager pager = new Pager();
        pager.setRows(drugstockMapper.searchDrugstockinsufficient(dto, offset, limit));
        pager.setTotal(drugstockMapper.searchDrugstockInsufficientCounr(dto));
        return pager;
    }

    @Override
    public List<Drugstock> searchKunCunNoFenYe(String drugNum) {
        return drugstockMapper.searchNoFenYe(drugNum);
    }

    /**
     * 批量采购
     *
     * @param stoNum
     * @return
     */
    @Override
    public Map<String, Purdetails> searchDan(String[] stoNum, Integer bh, HttpServletRequest req) {
        Map<String, Purdetails> map = new HashMap<>();
        for (int i = 0; i < stoNum.length; i++) {
            Drugstock drugstock = drugstockMapper.searchDan(stoNum[i]);//获取批量补货的药品库存编号
            Purdetails purdetails = new Purdetails();//创建采购详情对象
            String planNum = genNumUtil.getNum(purplanService.searchNewPurNum());//获取采购主表编号
            purdetails.setPlanNum(planNum);//给采购主表字段赋值
            purdetails.setDruginfo(drugstock.getDruginfo());//给采购详情里面的药品信息对象赋值
            purdetails.setDelQoh(drugstock.getStoPcs());//现有数量
            purdetails.setDelOneprice(drugstock.getStoPresell());//零售价格
            purdetails.setDelBuyprice(drugstock.getStoPrimecost());//购进价格
            purdetails.setDelRetailprice(drugstock.getStoPrimecost() - 2);//批发价格
            purdetails.setDelBuynum(bh);//购进数量
            purdetails.setDrugNum(drugstock.getDrugNum());//药品编号
            String keyId = purplanService.addDels2Map(purdetails, req);//添加到Map中
            map.put(keyId, purdetails);
        }
        return map;
    }

    @Override
    public List<Drugstock> searchOverDueDruginfo(DrugstockDto dto) {
        return drugstockMapper.searchOverdueDruginfo(dto);
    }

    @Override
    public List<Drugstock> searchDestoryDruginfo(String[] stoNum) {
        List<Drugstock> list = new ArrayList<>();
        if (stoNum != null && stoNum.length > 0) {
            for (int i = 0; i < stoNum.length; i++) {
                list.add(drugstockMapper.searchDetoryDruginfo(stoNum[i]));
            }
        }
        return list;
    }

    @Override
    public Integer addDestoryMasterAspect(Destorymaster destorymaster, String[] stoNum) {
        String oldNum = destorymasterMapper.searchNewDestoryNum();
        String newNum = genNumUtil.getNum(oldNum);
        if (newNum == null) {
            newNum = "YT0001";
        }
        destorymaster.setDesNum(newNum);//销毁编号
        destorymaster.setDesState(0);//销毁状态
        destorymaster.setDesAuditstate(0);//是否审核
        destorymaster.setDesSubdate(new Date());
        destorymasterMapper.addDestorymaster(destorymaster);
        Integer msg = 0;
        if (stoNum != null && stoNum.length > 0) {
            for (int i = 0; i < stoNum.length; i++) {
                Destorydetails destorydetails = new Destorydetails();
                destorydetails.setDesNum(newNum);
                destorydetails.setStoNum(stoNum[i]);
                Drugstock drugstock = drugstockMapper.searchDan(stoNum[i]);
                destorydetails.setDetLotnum(drugstock.getStoLotnum());
                destorydetails.setDrugNum(drugstock.getDrugNum());
                destorydetails.setDetNumber(drugstock.getStoPcs());
                destorydetails.setProNum(drugstock.getProNum());
                destorydetails.setDetPrimecost(drugstock.getStoPrimecost());
                msg = destorydetailsMapper.addDestoryDetails(destorydetails);
            }
        }
        return msg;
    }

    @Override
    public Pager searchDestoryRecord(DestoryDto dto, Integer offset, Integer limit) {
        Pager pager = new Pager();
        List<Destorymaster> list = destorymasterMapper.searchDestorymaster(dto, offset, limit);
        pager.setTotal(destorymasterMapper.total(dto));
        pager.setRows(list);
        return pager;
    }

    @Override
    public List<Destorydetails> searchDestoryDetailsSee(String desNum) {
        return destorydetailsMapper.searchDestoryDetails(desNum);
    }

    @Override
    public void DestoryDelete(String[] stoNum) {
        drugstockMapper.DestoryDelete(stoNum);
    }

    @Override
    public void updateDestoryState(String desNum) {
        destorymasterMapper.updateState(desNum);
    }

    @Override
    public List<Drugstock> searchStoLotnum(String drugNum) {
        return drugstockMapper.searchStoLotnum(drugNum);
    }


    //session
    public String addSessionMap(Drugstock drugstock, HttpServletRequest req) {
        HttpSession session = req.getSession();
        Map<String, Drugstock> map = null;
        if (session.getAttribute("takestoMap") == null) {
            map = new HashMap<>();
            session.setAttribute("takestoMap", map);
        }
        map = (Map<String, Drugstock>) session.getAttribute("takestoMap");
        Integer newId = map.size() + 1;
        //根据药品编号和批号获取u全部信息
        Drugstock drugstock1 = drugstockMapper.searchDrugstockByDrugNumandStoLotnum(drugstock.getDrugNum(), drugstock.getStoLotnum());
        drugstock1.setStoPcs(drugstock.getStoPcs());
        map.put(newId.toString(), drugstock1);

        //返回最新的编号
        return newId.toString();
    }

    @Override
    public Drugstock searchDrugstockByDrugNumandStoLitunm(String drugNum, String stoLotnum) {
        return drugstockMapper.searchDrugstockByDrugNumandStoLotnum(drugNum, stoLotnum);
    }

    @Override
    public List<Worker> searchAllWorker() {
        return workerMapper.searchAllWorker();
    }

    @Override
    public Integer addTakestoDrugstockAspect(Inventorying inventorying, Invdetails invdetails, HttpServletRequest req) {
        String oldNum = inventoryingMapper.searchBigInvNum();
        String newNum = "";
        if (oldNum == null) {
            newNum = "PD1001";
        } else {
            newNum = genNumUtil.getNum(oldNum);
        }
        inventorying.setInvNum(newNum);//盘点单号
        inventorying.setInvState(0);//盘点状态
        inventorying.setInvAuditstate(0);//审核状态
        //------------------------------------------
        inventoryingMapper.addDrugstockTakesto(inventorying);
        HttpSession session = req.getSession();
        Map<String, Drugstock> map = (Map<String, Drugstock>) session.getAttribute("takestoMap");
        Integer i = null;
        for (String keyId : map.keySet()) {
            Drugstock drugstock = map.get(keyId);
            invdetails.setInvNum(newNum);//盘点主表编号
            invdetails.setIndValiddate(drugstock.getStoValiddate());
            invdetails.setDrugNum(drugstock.getDrugNum());
            Drugstock drugstock1 = drugstockMapper.searchDrugstockByDrugNumandStoLotnum(drugstock.getDrugNum(), drugstock.getStoLotnum());
            invdetails.setIndStock(drugstock1.getStoPcs());
            invdetails.setIndAcstock(drugstock.getStoPcs());//修正库存
            invdetails.setIndUpstate(1);//修正状态
            invdetails.setInvLotnum(drugstock.getStoLotnum());//批号
            i = invdetailsMapper.addInvderByInventorying(invdetails);
        }
        return i;
    }

    @Override
    public Pager searchTakestoAll(TakestoDto dto,Integer offset, Integer limit) {
        Pager pager = new Pager();
        List<Inventorying> list = inventoryingMapper.searchTakestoAll(dto,offset, limit);

        for (Inventorying inventorying : list) {
            String woJubnum = inventorying.getInvPers();
            String[] woJubnums = woJubnum.split(",");
            StringBuffer sbf = new StringBuffer();
            for (String s : woJubnums) {
                Worker worker = workerMapper.searchDan(s);
                sbf.append(worker.getWoName() + ",");
            }
            sbf.deleteCharAt(sbf.length() - 1);
            inventorying.setInvPers(sbf.toString());
            Worker worker = workerMapper.searchDan(inventorying.getInvAuditper());
            inventorying.setInvAuditper(worker.getWoName());
        }
        pager.setRows(list);
        pager.setTotal(inventoryingMapper.total(dto));
        return pager;
    }

    @Override
    public Inventorying searchDan(String invNum) {
        Inventorying inventorying = inventoryingMapper.searchDan(invNum);
        String woJubnum = inventorying.getInvPers();
        String[] woJubnums = woJubnum.split(",");
        StringBuffer sbf = new StringBuffer();
        for (String s : woJubnums) {
            Worker worker = workerMapper.searchDan(s);
            sbf.append(worker.getWoName() + ",");
        }
        sbf.deleteCharAt(sbf.length() - 1);
        inventorying.setInvPers(sbf.toString());
        Worker worker = workerMapper.searchDan(inventorying.getInvAuditper());
        inventorying.setInvAuditper(worker.getWoName());
        return inventorying;
    }

    @Override
    public List<Invdetails> searchByInventorying(String invNum) {
        return invdetailsMapper.searchByInventoty(invNum);
    }

    @Override
    public Integer correctionTakesto(String invNum) {
        inventoryingMapper.updateTakestoState(invNum);//修改盘点状态
        List<Invdetails> list = invdetailsMapper.searchByInventoty(invNum);//获取该盘点的详细信息
        Integer i = 0;
        for (Invdetails invdetails:list){
            i=drugstockMapper.updateDrugStockStoPcs(invdetails.getIndAcstock(),invdetails.getDrugstock().getStoNum());//校正库存
        }
        return i;
    }
}